package handler

import (
	"github.com/gin-gonic/gin"
	"mime/multipart"
	"path/filepath"
	"zk333/api/respons"
	"zk333/pkg"
)

func Upload(c *gin.Context) {
	file, err := c.FormFile("file")
	if err != nil {
		respons.Error(c, -1, "文件获取失败")
	}
	// 校验文件上传类型
	fileType := map[string]bool{
		".png":  true,
		".jpg":  true,
		".jpeg": true,
		".gif":  true,
		".mp4":  true,
	}
	if !fileType[filepath.Ext(file.Filename)] {
		respons.Error(c, -1, "只能上传图片或视频格式文件")
		return
	}
	open, err := file.Open()
	if err != nil {
		respons.Error(c, -1, "文件读取失败")
		return
	}
	defer func(open multipart.File) {
		err = open.Close()
		if err != nil {

		}
	}(open)
	upload, err := pkg.Upload(file, open)
	if err != nil {
		respons.Error(c, -1, "文件上传失败")
		return
	}
	data := map[string]interface{}{
		"return_url": upload,
	}
	respons.Success(c, data)
}
